<html>
<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.0/socket.io.js"></script>
</head>
<body>
    <h1>聊天室</h1>
    <ul id="msgs"></ul>
    <ul id="messages"></ul>
    <input id="nickname" placeholder="请输入昵称">
    <input id="msg" placeholder="请输入消息">
    <button onclick="sendMsg()">发送</button>
</body>

<script>
    var socket = io();
    function sendMsg() {
        var nickename =document.getElementById("nickname").value;
        var msg =document.getElementById("msg").value;
        msg = nickename + ":" + msg + (new Date().toLocaleTimeString());
        socket.send(msg);
        createElement(msg);
    }
    //接受服务端发送的消息
    socket.on('message', function(message) {
        createElement(message);
    });
    function creteElement(msg){
        var li = document.createElement("li");
        li.textContent = msg;
        document.getElementById("messages").appendChild(li);
    }
</script>
</html>